package com.wcf.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

public class PanBaiduServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
        JSONArray r=new JSONArray();
        String q= URLEncoder.encode(req.getParameter("q"), "utf-8");
		String jsoncallback=req.getParameter("callback");
		String start=req.getParameter("start");
        if(start==null || start.length()==0){
            start="0";
        }

        if(q==null || q.length()==0 || jsoncallback==null || jsoncallback.length()==0){
            try {
                resp.setContentType("text/html;charset=utf-8");
                PrintWriter out=resp.getWriter();
                out.println(jsoncallback+"("+r.toString()+")");
                out.flush();
                out.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return;
        }
        String urlStr="https://www.googleapis.com/customsearch/v1element?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1gunmMikTzQqY&rsz=filtered_cse&num=10&hl=zh_CN&prettyPrint=false&source=gcsc&gss=.com&sig=b16e3ffbc96e4526fdc0cc8394bf713a&start="+start+"&cx=013895039659648421240:fwv79fiuhjm&q="+q+"&sort=date&googlehost=www.google.com";
        URL url = new URL(urlStr);

	    BufferedReader bufr = new BufferedReader(new InputStreamReader(new BufferedInputStream(url.openStream()),"utf-8"));
	    String line;
	    StringBuffer sb=new StringBuffer();
	    while((line = bufr.readLine())!=null){
	    	sb.append(line);
	    }
	    bufr.close();
        JSONObject jsonObject = JSON.parseObject(sb.toString());
        JSONArray results=jsonObject.getJSONArray("results");
        for(int i=0;i<results.size();i++){
            JSONObject j=(JSONObject) results.get(i);
            JSONObject o=new JSONObject();
            o.put("title", j.get("title"));
            o.put("content", j.get("content"));
            o.put("unescapedUrl", j.get("unescapedUrl"));
            r.add(o);
        }
        try {
	    	resp.setContentType("text/html;charset=utf-8");
			PrintWriter out=resp.getWriter();
			out.println(jsoncallback+"("+r.toString()+")");
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	

}
